/*******************************************************************************
 * Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
 * Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *******************************************************************************/
package com.qinyeit.webapp.security;

import lombok.extern.apachecommons.CommonsLog;
import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.MapCache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>ClassName: com.qinyeit.shirostarterdemo.security.RedisSessionDao
 * <p>Function: 使用redis来存储 session
 * <p>date: 2018-08-11 16:16
 *
 * @author wuqing
 * @version 1.0
 * @since JDK 1.8
 */
@CommonsLog
public class RedisSessionDao  extends CachingSessionDAO {

    private ShiroSessionRedisTemplate redisTemplate;
    private static final String KEY = "share:redis:session:hash";

    public RedisSessionDao(ShiroSessionRedisTemplate redisTemplate) { //设置缓存
        this.redisTemplate=redisTemplate;
        setCacheManager(new AbstractCacheManager() {
            @Override
            protected Cache<Serializable, Session> createCache(String name) throws CacheException {
                return new MapCache<Serializable, Session>(name, new ConcurrentHashMap<Serializable, Session>());
            }
        });
    }

    @Override
    protected Serializable doCreate(Session session) {
        log.debug("shiro session redis op doCreate...........");
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        //添加进redis
        this.hadd(sessionId.toString(), session);

        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.debug("shiro session redis op doReadSession...........");
        return this.hget(sessionId.toString());
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        log.debug("shiro session redis op update...........");
        if(session == null || session.getId() == null){
            log.debug("Session is null");
            return;
        }
        Serializable sessionId = session.getId();
        this.hadd(sessionId.toString(), session);
    }

    @Override
    protected void doUpdate(Session session) {
        log.debug("无需做任何操作,该方法永远不会被调用");
    }

    @Override
    public void delete(Session session) {
        log.debug("shiro session redis op delete...........");
        if(session == null || session.getId() == null){
           log.debug("Session is null");
            return;
        }
        this.hdelete(session.getId().toString());
    }

    @Override
    protected void doDelete(Session session) {
        log.debug("无需做任何操作,该方法永远不会被调用");
    }

    @Override
    public Collection<Session> getActiveSessions() {
        log.debug("shiro session redis op getActiveSessions...........");
        List<Session> list = this.hmget();
        return list;
    }


    public void hadd(String sessionId, Session session){
        redisTemplate.boundHashOps(KEY).put(sessionId, session);
    }

    public void hdelete(String sessionId){
        redisTemplate.boundHashOps(KEY).delete(sessionId);
    }

    public Session hget(String sessionId){
        return (Session) redisTemplate.boundHashOps(KEY).get(sessionId);
    }

    public List<Session> hmget(){
        List<Session> list = new ArrayList<>();

        List<Object> values = redisTemplate.boundHashOps(KEY).values();
        for (Object object : values) {
            list.add((Session) object);
        }
        return list;
    }
}
